import 'dart:async';
import 'dart:math';

import 'package:factoryside/bean/statistics_entity.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class BarChartSample1 extends StatefulWidget {
  List<StatisticsEntity> statisticsList = [];

  BarChartSample1(this.statisticsList);

  final List<Color> availableColors = [
    Colors.purpleAccent,
    Colors.yellow,
    Colors.lightBlue,
    Colors.orange,
    Colors.pink,
    Colors.redAccent,
  ];

  @override
  State<StatefulWidget> createState() => BarChartSample1State();
}

class BarChartSample1State extends State<BarChartSample1> {
  final Color barBackgroundColor = const Color(0xff72d8bf);
  final Duration animDuration = const Duration(milliseconds: 250);

  int touchedIndex = -1;

  bool isPlaying = false;

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 1,
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)),
//        color: const Color(0xff81e5cd),
        elevation: 0,
        child: Stack(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisAlignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Text(
                    '发单区域统计',
                    style: TextStyle(
                        color: const Color(0xff0f4a3c),
                        fontSize: 24,
                        fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(
                    height: 38,
                  ),
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 0),
                      child: BarChart(
                        isPlaying ? randomData() : mainBarData(),
                        swapAnimationDuration: animDuration,
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 12,
                  ),
                ],
              ),
            ),
//            Padding(
//              padding: const EdgeInsets.all(8.0),
//              child: Align(
//                alignment: Alignment.topRight,
//                child: IconButton(
//                  icon: Icon(
//                    isPlaying ? Icons.pause : Icons.play_arrow,
//                    color: const Color(0xff0f4a3c),
//                  ),
//                  onPressed: () {
//                    setState(() {
//                      isPlaying = !isPlaying;
//                      if (isPlaying) {
//                        refreshState();
//                      }
//                    });
//                  },
//                ),
//              ),
//            )
          ],
        ),
      ),
    );
  }

  BarChartGroupData makeGroupData(
    int x,
    double y, {
    bool isTouched = false,
    Color barColor = Colors.red,
    double width = 10,
    List<int> showTooltips = const [],
  }) {
    return BarChartGroupData(
      x: x,
      barRods: [
        BarChartRodData(
          y: isTouched ? y + 1 : y,
          colors: isTouched ? [Colors.yellow] : [barColor],
          width: width,
          borderRadius: BorderRadius.circular(0),
          backDrawRodData: BackgroundBarChartRodData(
            show: false,
            y: (widget.statisticsList[0].count + 100).toDouble(),
            colors: [barBackgroundColor],
          ),
//          rodStackItems: [
//            BarChartRodStackItem(0, 300, Colors.red),
//            BarChartRodStackItem(3, 600, Colors.green),
//            BarChartRodStackItem(6, 900, Colors.blue),
//          ]
        ),
      ],
      showingTooltipIndicators: showTooltips,
    );
  }

  List<BarChartGroupData> showingGroups() => List.generate(7, (i) {
        return makeGroupData(i, Random().nextInt(1000).toDouble(),
            isTouched: i == touchedIndex);
      });

  BarChartData mainBarData() {
    int maxY = widget.statisticsList[0].count;
    var interval = roundInterval(maxY / 5).toDouble();
    return BarChartData(
      barTouchData: BarTouchData(
        touchTooltipData: BarTouchTooltipData(
            tooltipBgColor: Colors.blueGrey,
            getTooltipItem: (group, groupIndex, rod, rodIndex) {
              String weekDay = widget.statisticsList[group.x.toInt()].name;
              return BarTooltipItem(
                weekDay + '\n',
                TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                ),
                children: <TextSpan>[
                  TextSpan(
                    text: '${(rod.y - 1).toInt().toString()}单',
                    style: TextStyle(
                      color: Colors.yellow,
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              );
            }),
        touchCallback: (barTouchResponse) {
          setState(() {
            if (barTouchResponse.spot != null &&
                barTouchResponse.touchInput is! PointerUpEvent &&
                barTouchResponse.touchInput is! PointerExitEvent) {
              touchedIndex = barTouchResponse.spot.touchedBarGroupIndex;
            } else {
              touchedIndex = -1;
            }
          });
        },
      ),
      titlesData: FlTitlesData(
        show: true,
        bottomTitles: SideTitles(
          showTitles: true,
          getTextStyles: (context, value) => const TextStyle(
              color: Colors.black, fontWeight: FontWeight.bold, fontSize: 14),
          margin: 16,
          getTitles: (double value) {
//            var title = '新疆维吾尔自治区自弃去新疆维吾尔自治区自弃去';
            var title = widget.statisticsList[value.toInt()].name;
            var row = (title.length / 3).ceil();
            if (row > 1) {
              //超过三个字换行显示
              var newParamsName = "";
              for (int i = 0; i < row; i++) {
                var tempStr = "";
                var start = i * 3;
                var end = start + 3;
                if (i == row - 1) {
                  tempStr = title.substring(start, title.length);
                } else {
                  tempStr = title.substring(start, end) + "\n";
                }
                newParamsName += tempStr;
              }
              title = newParamsName;
            }
            print('行数：$row');
            return title;
          },
        ),
        leftTitles: SideTitles(
          showTitles: true,
          getTextStyles: (context, value) => const TextStyle(
            color: Colors.black,
            fontSize: 11,
          ),
          getTitles: (value) {
            var i = value.toInt();
//            print('maxY:$maxY');
            print('纵坐标:$i');
            if (i == interval * 0 ||
                i == interval * 1 ||
                i == interval * 2 ||
                i == interval * 3 ||
                i == interval * 4 ||
                i == interval * 5) {
              return formatNumber(value);
            }
            return '';
          },
          margin: 10,
          interval: interval,
          reservedSize: 22,
        ),
      ),
      borderData: FlBorderData(
        show: true,
        border: const Border(
          bottom: BorderSide(
            color: Colors.black,
            width: 1,
          ),
          left: BorderSide(
            color: Colors.black,
            width: 1,
          ),
          right: BorderSide(
            color: Colors.transparent,
          ),
          top: BorderSide(
            color: Colors.transparent,
          ),
        ),
      ),
      minY: 0,
      maxY: maxY.toDouble(),
      barGroups: List.generate(widget.statisticsList.length, (i) {
        return makeGroupData(i, widget.statisticsList[i].count.toDouble(),
            width: 50, isTouched: i == touchedIndex);
      }),
    );
  }

  BarChartData randomData() {
    return BarChartData(
      barTouchData: BarTouchData(
        enabled: false,
      ),
      titlesData: FlTitlesData(
        show: true,
        bottomTitles: SideTitles(
          showTitles: true,
          getTextStyles: (context, value) => const TextStyle(
              color: Colors.black, fontWeight: FontWeight.bold, fontSize: 14),
          margin: 16,
          getTitles: (double value) {
            switch (value.toInt()) {
              case 0:
                return '广东';
              case 1:
                return '浙江';
              case 2:
                return '上海';
              case 3:
                return '福建';
              case 4:
                return '江西';
              case 5:
                return '北京';
              case 6:
                return '湖北';
              default:
                return '';
            }
          },
        ),
        leftTitles: SideTitles(
          showTitles: false,
        ),
      ),
      borderData: FlBorderData(
        show: false,
      ),
      barGroups: List.generate(7, (i) {
        switch (i) {
          case 0:
            return makeGroupData(0, Random().nextInt(1000).toDouble() + 6,
                barColor: widget.availableColors[
                    Random().nextInt(widget.availableColors.length)]);
          case 1:
            return makeGroupData(1, Random().nextInt(1000).toDouble() + 6,
                barColor: widget.availableColors[
                    Random().nextInt(widget.availableColors.length)]);
          case 2:
            return makeGroupData(2, Random().nextInt(1000).toDouble() + 6,
                barColor: widget.availableColors[
                    Random().nextInt(widget.availableColors.length)]);
          case 3:
            return makeGroupData(3, Random().nextInt(1000).toDouble() + 6,
                barColor: widget.availableColors[
                    Random().nextInt(widget.availableColors.length)]);
          case 4:
            return makeGroupData(4, Random().nextInt(1000).toDouble() + 6,
                barColor: widget.availableColors[
                    Random().nextInt(widget.availableColors.length)]);
          case 5:
            return makeGroupData(5, Random().nextInt(1000).toDouble() + 6,
                barColor: widget.availableColors[
                    Random().nextInt(widget.availableColors.length)]);
          case 6:
            return makeGroupData(6, Random().nextInt(1000).toDouble() + 6,
                barColor: widget.availableColors[
                    Random().nextInt(widget.availableColors.length)]);
          default:
            return throw Error();
        }
      }),
    );
  }

  Future<dynamic> refreshState() async {
    setState(() {});
    await Future<dynamic>.delayed(
        animDuration + const Duration(milliseconds: 50));
    if (isPlaying) {
      await refreshState();
    }
  }
}
